//
//  RealtimeTranslationPopupConfig.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/13.
//

import UIKit
import HandyJSON

class RealtimeTranslationPopupConfig: BaseModel {
    // 总次数
    var num: Int = 0
    var messageZh: String = ""
    var messageRu: String = ""
    /// 倒计时的次数
    var time: Int = 0
    
    // 存储属性，记录触发次数
    var showCount: Int = 0
    // 记录最后一次显示时间
    var lastime: Int = 0
    /// 显示内容
    var content: String {
        LanguageManager.isLanguageZH ? messageZh: messageRu
    }
    
    override func mapping(mapper: HelpingMapper) {
        mapper <<< [
            messageZh <-- "desc",
            messageRu <-- "desc_ru",
        ]
    }
    
    override func didFinishMapping() {
        lastime = Date.sg.timestamp()
        
        //        num = 3
        //        time = 5
        //        messageZh = "环境噪音可能导致识别不准确，影响翻译质量。请尽量在安静环境下使用，确保语音清晰，以获得最佳翻译效果。"
        //        messageRu = "Фоновый шум может снизить точность распознавания и качество перевода. Для лучшего результата используйте приложение в тихом месте и чётко произносите фразы."
    }
}


class RealtimeTranslationPopupManager {
    
    static let shared = RealtimeTranslationPopupManager()
    private init() {}
    // 要配置当前用户的id
    private var userId: String = ""
    private let userDefaults = UserDefaults.standard
    
}

extension RealtimeTranslationPopupManager {
    // 存储相关方法（更新为支持用户ID）
    func save(_ config: RealtimeTranslationPopupConfig) {
        userId = String(UserProfile.userId)
        
        if let model = fetch() {
            
            if !isTodayAsLastData() {
                // 最后一次显示时间,不是今天的,重新计数,更新时间
                model.showCount = 0
            }
            
            // 已经存储过了,需要更新内容,
            model.num = config.num
            model.lastime = config.lastime
            model.messageZh = config.messageZh
            model.messageRu = config.messageRu
            model.time = config.time
            // 还没有存储过,需要保存最新的
            let dataDictionary = JsonUtil.dictionaryFromModel(model)
            let jsonString = dataDictionary.toJSONString()
            userDefaults.set(jsonString, forKey: configKey(for: userId))
            
        } else {
            // 还没有存储过,需要保存最新的
            let dataDictionary = JsonUtil.dictionaryFromModel(config)
            let jsonString = dataDictionary.toJSONString()
            userDefaults.set(jsonString, forKey: configKey(for: userId))
            
        }
    }
    
    /// 拉取本地数据
    func fetch() -> RealtimeTranslationPopupConfig? {
        
        if userId.isEmpty { return nil }
        
        let key = configKey(for: userId)
        
        guard let jsonString = UserDefaults.standard.string(forKey: key) else { return nil }
        
        guard let dataDictionary = jsonString.toDictionary() else { return nil }
        
        return JsonUtil.modelFromDictionary(dataDictionary, RealtimeTranslationPopupConfig.self)
        
    }
    
    /// 判断是否还有更多的显示次数
    /// - Returns: true: 还有更多的次数, false: 已经没有次数了
    func isMoreTime() -> Bool {
        if let model = fetch() {
            if model.showCount < model.num {
                // 还有次数
                addShowCount()
                return true
            }
        }
        xLog("[PopupManager] 没有显示次数了")
        return false
    }
    
    /// 打印本地存储数据
    func printData() {
        let key = configKey(for: userId)
        
        let jsonString = UserDefaults.standard.string(forKey: key)!
        
        let dataDictionary = jsonString.toDictionary()!
        
        xLog("[PopupManager] 本地存储的数据 \(dataDictionary as NSDictionary)")
    }
    
    
    /// 清除所有用户的数据（谨慎使用）
    func clearAllData() {
        // 找出所有包含特定前缀的key
        let keys = userDefaults.dictionaryRepresentation().keys
        let popupKeys = keys.filter { $0.hasPrefix(configKey(for: "")) }
        popupKeys.forEach { key in
            userDefaults.removeObject(forKey: key)
        }
    }
    
    /// 清除特定用户的数据
    func clearData() {
        userDefaults.removeObject(forKey: configKey(for: userId))
    }
    
}

private extension RealtimeTranslationPopupManager {
    
    func configKey(for userId: String) -> String {
        return "kRealtimeTranslationDialogDefaultsKey_\(userId)"
    }
    
    /// 检查最后显示日期是否是今天
    /// - Parameter userId: 用户ID
    /// - Returns: 如果是同一天返回true，否则false
    private func isTodayAsLastData() -> Bool {
        if let model = fetch() {
            if Date.sg.date(from: model.lastime).sg.isToday {
                // 判断最后一条数据是不是今天
                return true
            }
        }
        return false
    }
    
    
    /// 增加显示次数计数, 更新显示时间
    private func addShowCount() {
        if let model = fetch() {
            model.showCount += 1
            model.lastime = Date.sg.timestamp()
            
            // 更新
            let dataDictionary = JsonUtil.dictionaryFromModel(model)
            let jsonString = dataDictionary.toJSONString()
            userDefaults.set(jsonString, forKey: configKey(for: userId))
        }
    }
}
